package com.project.config;

import com.project.bean.PowerBean;
import com.project.bean.UserBean;
import com.project.dao.PowerDao;
import com.project.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;


@Component
public class MyRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Resource
    private PowerDao powerDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UserBean user = (UserBean) principalCollection.getPrimaryPrincipal();
        //用户查询权限
        List<PowerBean> list = powerDao.findAllPowerByUserName(user.getUserName());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        list.stream().filter(power ->power!=null&&!power.getPowerResource().equals(""))
                .forEach(powerBean ->{
                    info.addStringPermission(powerBean.getPowerResource());
                });
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName = token.getUsername();
        char[] pwdArray= token.getPassword();
        String pwd = String.valueOf(pwdArray);
//        数据库查询用户是否存在
//        UserBean user = userDao.findDistinctByUserNameAndPwd(userName,pwd);
        UserBean user =userService.login(userName,pwd);
        System.out.println(user);
        if (user!=null){
          return new SimpleAuthenticationInfo(user,pwd,userName);
        }
        return null;
    }
}
